package framework.grid.data;


import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.TreeMap;

public class RemoteNodeData extends UnicastRemoteObject implements IRemoteNodeData {
	private TreeMap<String,ArrayList<String>> values = new TreeMap<String,ArrayList<String>>();
	
	public RemoteNodeData() throws RemoteException {
		super();
	}
	
	
	@Override
	public String[] get(String key) throws RemoteException   {
		String[] copy = null;
		ArrayList<String> list = this.values.get(key);
		if (list!=null) {
			copy = new String[list.size()];
			list.toArray(copy);
		}
		
		return copy;
	}
	
	@Override
	public void put(String key, String value) throws RemoteException  {
		ArrayList<String> list = this.values.get(key);
		if (list==null) {
			list = new ArrayList<String>();
			this.values.put(key, list);
		}
		
		list.add(value);
	}
	

	@Override
	public String[] remove(String key) throws RemoteException {
		String[] copy = null;
		ArrayList<String> list = this.values.remove(key);
		if (list!=null) {
			copy = new String[list.size()];
			list.toArray(copy);
		}
		
		return copy;
	}
	
	
	@Override
	public void setValues(TreeMap<String, ArrayList<String>> values) throws RemoteException {
		this.values = values;
	}

	@Override
	public TreeMap<String, ArrayList<String>> getValues() throws RemoteException {
		return values;
	}

	public static void splitData(TreeMap<String,ArrayList<String>> lowerMap, 
			String splitBarrier, TreeMap<String,ArrayList<String>> higherMap) {
		TreeMap<String,ArrayList<String>> union = new TreeMap<String,ArrayList<String>>();
		union.putAll(lowerMap);
		union.putAll(higherMap);
		
		lowerMap.clear();
		higherMap.clear();
		
		lowerMap.putAll(union.headMap(splitBarrier));
		higherMap.putAll(union.tailMap(splitBarrier));
	}
	
}
